<template>
    <a-modal
        :title="isEdit ? '编辑' : '新增'"
        :open="props.open"
        @update:open="emit('update:open', $event)"
        @ok="handleSubmit"
        @cancel="handleCancel"
        :confirm-loading="confirmLoading"
    >
        <dynamic-form-edit-v1
            ref="dynamicFormRef"
            :form-items="formItems"
            :initial-values="props.record"
            layout="vertical"
        ></dynamic-form-edit-v1>
    </a-modal>
</template>

<script setup lang="ts">
import type { SysUserVo, UpdateSysUserDto } from "@/api/globals";
import type { FormItemConfig } from "@/components/dynamic-form/types/form-config";

const props = defineProps<{
    open: boolean;
    record?: SysUserVo | null; // 回显数据，编辑时传入，新增时为 null 或 undefined
}>();

const emit = defineEmits<{
    (e: "update:open", value: boolean): void;
    (e: "success"): void;
}>();

// 表单引用
const dynamicFormRef = ref();

interface CreateSysUserDto {
    username: string;
    password: string;
}

const formItems: FormItemConfig<Partial<UpdateSysUserDto & CreateSysUserDto>>[] = [
    {
        type: "input",
        name: "username",
        label: "用户名",
        rules: [{ required: true, message: "请输入用户名", whitespace: true }],
        componentProps: {
            placeholder: "请输入用户名"
        }
    },
    {
        type: "input-password",
        name: "password",
        label: "密码",
        rules: [{ required: true, message: "请输入密码", whitespace: true }],
        componentProps: {
            placeholder: "请输入密码"
        }
    },
    {
        type: "input",
        name: "nickname",
        label: "昵称",
        rules: [{ required: true, message: "请输入昵称", whitespace: true }],
        componentProps: {
            placeholder: "请输入昵称"
        }
    },
    {
        type: "input",
        name: "email",
        label: "邮箱",
        rules: [
            { required: true, message: "请输入邮箱" },
            { type: "email", message: "请输入正确的邮箱地址" }
        ],
        componentProps: {
            placeholder: "请输入邮箱"
        }
    },
    {
        type: "input",
        name: "phone",
        label: "手机号",
        rules: [
            { required: true, message: "请输入手机号" },
            { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" }
        ],
        componentProps: {
            placeholder: "请输入手机号"
        }
    }
];

// 是否为编辑模式
const isEdit = computed(() => !!props.record?.id);

// 确认加载状态
const confirmLoading = ref(false);

// 提交表单
const handleSubmit = async () => {
    try {
        const values = await dynamicFormRef.value.validateFields();
        confirmLoading.value = true;

        if (isEdit.value) {
            // 调用编辑 API
            await Apis.SysUser.update({
                pathParams: { id: props.record!.id },
                data: values
            });
        } else {
            // 调用新增 API
            await Apis.SysUser.create({ data: values });
        }

        emit("success"); // 通知父组件刷新
        handleCancel(); // 关闭弹窗
    } catch (error) {
        console.error("表单提交失败:", error);
    } finally {
        confirmLoading.value = false;
    }
};

// 取消/关闭
const handleCancel = () => {
    emit("update:open", false);
    //   // 可选：关闭时重置表单
    dynamicFormRef.value?.clearValidate();
};
</script>
